package com.wyc.aop;

import com.alibaba.fastjson.JSONObject;
import com.wyc.mapper.OperateLogMapper;
import com.wyc.pojo.OperateLog;
import com.wyc.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.wyc.anno.Log)")
    public  Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //从请求头中拿到jwt，最终获取jwt中保存的id
        String token = httpServletRequest.getHeader("token");
        Claims claims = jwtUtils.parse(token);
        System.out.println(claims);

        Integer operateuser =Integer.parseInt(claims.get("id").toString());
        LocalDateTime operateTime = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String methodParams = Arrays.toString(joinPoint.getArgs());
        long begin=System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end=System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);
        long costTime=end-begin;

        OperateLog operateLog = new OperateLog(null,operateuser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.add(operateLog);

        return result;


    }
}
